using System.Collections;
using System.Collections.Generic;
using Spine;
using Spine.Unity;
using UnityEngine;

public class commonSpineDestroy : MonoBehaviour
{
    public float destroyDelay = 0f; // 倒计时秒数，默认为0
    private bool isAnimationCompleted = false;
    private SkeletonGraphic sp;

    // Start is called before the first frame update
    void Start()
    {
        // 获取skeleton组件
        sp = transform.Find("sp").GetComponent<SkeletonGraphic>();
        
        // 添加动画完成监听
        sp.AnimationState.Complete += OnAnimationComplete;
        
        // 如果设置了倒计时，则启动倒计时协程
        if (destroyDelay > 0)
        {
            StartCoroutine(DestroyAfterDelay());
        }
    }

    // Update is called once per frame
    private void OnAnimationComplete(TrackEntry trackEntry)
    {
        isAnimationCompleted = true;
        
        // 如果倒计时为0，则动画完成后立即销毁
        if (destroyDelay <= 0)
        {
            Destroy(gameObject);
        }
    }
    
    private IEnumerator DestroyAfterDelay()
    {
        yield return new WaitForSeconds(destroyDelay);
        Destroy(gameObject);
    }
    
    private void OnDestroy()
    {
        // 清理事件监听，避免内存泄漏
        if (sp != null && sp.AnimationState != null)
        {
            sp.AnimationState.Complete -= OnAnimationComplete;
        }
    }
}
